const app = getApp()
const promisify = require('../../utils/promisify')

Page({
  data: {
    items: [], //所有商品列表
    localCart: [], //购物车数组
    parentId: undefined, //父类的id
    total: 0, //收藏夹总价格
    showCart: false, //是否显示购物车
    count: 0, //购物车商品数量
    isLoaded: false, //是否请求到数据
    isRefreshing: false,
    isLoadingMoreData: false,
    hasMoreData: true,
    pendding: [], //等待发送请求的列表
    page: 1,
    pages: 1
  },
  onLoad: function (data) {
    let that = this
    let parentId = data.id
    promisify(wx.request)({
      url: `https://www.cumthing.world/cumthing/products/list2` + app.ToParams({
        parentId: parentId,
        page: that.data.page
      }),
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 默认值
      }
    }).then(
      data => {
        // 向items中添加一些本地页面展示需要的信息
        data = data.data.data
        data.list.forEach((item, index) => {
          item.index = index
          item.parentId = parentId
        })
        // 初始化数据
        that.setData({
          items: data.list,
          parentId: parentId,
          page: that.data.page + 1,
          pages: data.pages
        })
      },
      err => {
        console.log(err)
      }
    ).then(
      data => {
        /**
         * 因为异步调用的问题，在这里调用onShow
         * 并设置isLoaded为true
         * 调用onShow函数
         */
        that.setData({
          isLoaded: true
        })
        that.onShow()
      }
    )
  },

  onShow: function () {
    /**
     * 获取本地存储的购物车信息,将本地存储和请求下来的数据结合
     * 根据购物车中的物品数量，改变对应id的物品的数量
     * 只有isLoad的之后才能执行
     **/
    let that = this
    if (that.data.isLoaded) {
      let parentId = that.data.parentId
      that.setData({
        localCart: app.globalData.globalCart[parentId - 1].items
      })
      let localCart = that.data.localCart
      let items = that.data.items

      items.forEach((item, index) => {
        /**
         * 先重置所有物品的状态
         */
        item.subStyle = "cannotsub"
        item.addStyle = "canadd"
        item.num = 0
      })
      localCart.forEach((item, index) => {
        // 再根据GlobalCart改变所有物品的状态
        let id = item.id
        let num = item.num
        let addStyle = item.addStyle
        let subStyle = item.subStyle
        items.forEach((d, i) => {
          /** 
           * 找到该物品在列表中的位置，并修改列表数据中的数量
           */
          if (d.id === id) {
            d.num = num
            d.addStyle = addStyle
            d.subStyle = subStyle
          }
        })
      })

      that.setData({
        items: items
      })
      that.totalChange()
    }
  },

  totalChange: function () {
    /**
     * 计算总价和总数量的函数
     */
    let that = this
    let count = 0
    let total = 0
    let items = that.data.items
    items.forEach((item, index) => {
      count += item.num
      total += item.num * item.price
    })
    if (count === 0) {
      that.setData({
        count,
        total,
        showCart: false
      })
    } else {
      that.setData({
        total,
        count,
      })
    }
  },

  change: function (e) {
    /**
     * 点击加减时触发的函数
     */
    let that = this
    let method = e.target.dataset.method
    let index = e.target.dataset.index
    let item = that.data.items[index]
    let num = item.num
    let findNum = "items[" + index + "].num" //用来在小程序中修改数组
    let findSubStyle = "items[" + index + "].subStyle"

    if (app.loginFirst()) {
      if (method === "sub") {
        // 减
        if (num != 0) {
          num = num - 1
          that.setData({
            [findNum]: num
          })
        }
        if (num === 0) {
          that.setData({
            [findSubStyle]: "cannotsub"
          })
        }
      } else if (method === "add") {
        // 加
        num = num + 1
        that.setData({
          [findNum]: num,
          [findSubStyle]: "cansub"
        })
      }
      that.totalChange()
      that.changeStorage(item)
      if (!that.data.pendding[index]) {
        that.data.pendding[index] = app.throttle(app.postItemChange, 2000)
      }
      that.data.pendding[index](item)
    }
  },

  changeStorage: function (item) {
    /**
     * 更新某一商品全局数据globalData和本地缓存localStorage
     * 传入item
     */
    let id = item.id
    let num = item.num
    let parentId = item.parentId
    let that = this
    let flag = false //用来查看购物车是否已经有这个物品的数据
    let localCart = that.data.localCart
    localCart.forEach((item, index) => {
      /**
       * 遍历购物车，根据商品id找到这个商品
       */
      if (item.id === id) {
        // localCart中有这个物品的数据，就直接修改
        if (num != 0) {
          // 如果数量不为0，则修改
          item.num = num
          item.subStyle = "cansub"
        } else if (num === 0) {
          // 如果数量为0，删除这条数据
          localCart.splice(index, 1)
        }
        flag = true
      }
    })
    that.setData({
      localCart
    })
    app.globalData.globalCart[parentId - 1].items = localCart

    if (flag === false && num != 0) {
      /**
       * 没有这个商品就添加信息 
       * localCart和globalCart的数据结构
       */
      console.log(item)
      let index = localCart.length
      let findLocalCart = "localCart[" + index + "]"
      let name = item.name
      let brief = item.brief
      let img = item.main_image
      let price = item.price
      let parentId = item.parentId
      let obj = {
        id,
        num,
        name,
        brief,
        img,
        price,
        parentId,
        select: true,
        subStyle: "cannotsub",
        addStyle: "canadd"
      }
      that.setData({
        [findLocalCart]: obj
      })
      app.globalData.globalCart[parentId - 1].items[index] = obj
    }

    // 存储到本地缓存
    promisify(wx.setStorage)({
      key: "globalCart",
      data: app.globalData.globalCart
    })
  },
  showCart: function (e) {
    /**
     * 点击下方悬浮框时出现购物车
     */
    let that = this
    if (e.target.id != "buy") {
      let count = that.data.count
      if (count) {
        // 只有数量 >0 的时候才展示
        let showCart = !that.data.showCart
        that.setData({
          showCart: showCart
        })
      }
    }
  },
  hideCart: function () {
    let that = this
    let showCart = that.data.showCart
    if (showCart) {
      that.setData({
        showCart: !showCart
      })
    }
  },
  clean: function () {
    /**
     * 清空购物车
     */
    let that = this
    let parentId = that.data.parentId
    let items = that.data.items
    items.forEach((item, inxex) => {
      item.num = 0
      item.subStyle = "cannotsub"
    })
    // 修改本地缓存和globalData
    that.setData({
      items,
      localCart: [],
      count: 0,
      total: 0,
      showCart: false
    })
    app.globalData.globalCart[parentId - 1].items = []
    promisify(wx.setStorage)({
      key: "globalCart",
      data: app.globalData.globalCart
    }).then(
      data => {
        console.log("清除")
      },
      error => {
        console.log(error)
      }
    )
  },
  onReachBottom: function () {
    /**
     * 加载更多
     */
    let that = this
    let items = that.data.items
    let isLoadingMoreData = that.data.isLoadingMoreData
    let parentId = that.data.parentId
    if (that.data.pages < that.data.page) {
      that.setData({
        hasMoreData: false
      })
      return
    }
    if (isLoadingMoreData === false) {
      that.setData({
        isLoadingMoreData: true
      })
      promisify(wx.request)({
        url: `https://www.cumthing.world/cumthing/products/list2` + app.ToParams({
          parentId: parentId,
          page: that.data.page
        }),
        method: 'GET',
        header: {
          'Content-Type': 'application/json' // 默认值
        }
      }).then(
        data => {
          let list = data.data.data.list
          let length = that.data.items.length
          list.forEach((item, index) => {
            item.parentId = parentId
            item.index = index + length
            items.push(item)
          })
          that.setData({
            items: items,
            isLoadingMoreData: false,
            page: that.data.page + 1
          })
          that.onShow()
        }
      )
    }
  }
})